package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.config.BaseContext;
import com.itheima.config.ParamConfig;
import com.itheima.po.Employee;
import com.itheima.po.R;
import com.itheima.service.EmployeeServcie;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * @Author Andy
 * @Description //TODO EmployeeController
 * @Date 2022/3/8 10:59 上午
 * @Version 1.0
 **/
@RequestMapping("/employee")
@RestController
public class EmployeeController {

    @Autowired
    private EmployeeServcie employeeServcie;

    @RequestMapping("/login")
    public R<Employee> login(@RequestBody Employee employee,
                             HttpSession httpSession){
//        处理逻辑如下：
//1、将页面提交的密码password进行md5加密处理
        if (null == employee || StringUtils.isBlank(employee.getUsername())
                || StringUtils.isBlank(employee.getPassword())){
            return R.error("用户名或密码不可为空");
        }
//        DigestUtils.md5DigestAsHex 生成一个md5的加密
        String passwordMd5 = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
//2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        employeeLambdaQueryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee employeeInDb = employeeServcie.getOne(employeeLambdaQueryWrapper);
//3、如果没有查询到则返回登录失败结果
//        注意 不要用错对象 是employeeInDb
        if (null == employeeInDb){
            return R.error("用户或密码不正确");
        }
//4、密码比对，如果不一致则返回登录失败结果
        if (!passwordMd5.equals(employeeInDb.getPassword())){
            return R.error("用户或密码有误");
        }
//5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
//        0为禁用 1为启用
        if (employeeInDb.getStatus() == 0){
            return R.error("用户已禁用，请联系管理员");
        }
//6、登录成功，将员工id存入Session并返回登录成功结果
        httpSession.setAttribute("employeeId", employeeInDb.getId());
        return R.success(employeeInDb);
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public R<String> logout(HttpSession httpSession){
//        清掉session
        httpSession.removeAttribute("employeeId");
        return R.success("");
    }

//    Request URL: http://localhost:8080/employee
//Request Method: POST
    @PostMapping("")
    public R<String> save(@RequestBody Employee employee, HttpSession httpSession){

//        {"name":"ww","phone":"15012345678","sex":"1",
//        "idNumber":"210782197739476283","username":"qqq"}
        System.out.println("employee save thread id" + Thread.currentThread().getId());

//        1 补充缺少的字段 密码 初始密码123456 创建人 创建时间 更新人 更新时间
//        （状态数据库填充，当然也可以手动添加）
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setCreateUser((Long) httpSession.getAttribute("employeeId"));
//        employee.setUpdateUser((Long) httpSession.getAttribute("employeeId"));
//
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//        2 service调用save方法进行保存
//        try catch
        employeeServcie.save(employee);
        return R.success("添加成功");
    }
//    Request URL: http://localhost:8080/employee/page?page=1&pageSize=10&name=test
//Request Method: GET
    @Autowired
    private ParamConfig paramConfig;
    @GetMapping("/page")
    public R<Page<Employee>> page(Integer page, Integer pageSize, String name){
        Page<Employee> pageResult = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> lambdaQueryWrapper  = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotBlank(name), Employee::getName, name);
//        employeeServcie.page(pageResult, lambdaQueryWrapper);返回值与入参pageResult是同一个，所以用哪个都行
        employeeServcie.page(pageResult, lambdaQueryWrapper);
        System.out.println(paramConfig);

        return R.success(pageResult);
    }

//    修改状态
    @PutMapping()
    public R<String> update(@RequestBody Employee employee, HttpSession httpSession){
//        id status可以接到
//        更新 更新时间 更新人
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser((Long) httpSession.getAttribute("employeeId"));
//        service调用
        employeeServcie.updateById(employee);
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        return R.success(employeeServcie.getById(id));
    }

}
